const jwt = require('jsonwebtoken');
const { AppError } = require('../utils/errorHandler');
const { StatusCodes } = require('http-status-codes');

// 验证令牌
exports.authenticateToken = (req, res, next) => {
    try {
        // 获取 Authorization 头
        const authHeader = req.headers.authorization;
        console.log('Authorization header:', authHeader);

        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            console.log('未提供有效的认证令牌');
            throw new AppError('未提供有效的认证令牌', StatusCodes.UNAUTHORIZED);
        }

        // 提取令牌
        const token = authHeader.split(' ')[1];
        console.log('提取的令牌:', token);

        if (!token) {
            console.log('令牌为空');
            throw new AppError('令牌为空', StatusCodes.UNAUTHORIZED);
        }

        // 验证令牌
        try {
            const decoded = jwt.verify(token, process.env.JWT_SECRET);
            console.log('解码后的令牌:', decoded);
            req.user = decoded;
            next();
        } catch (verifyError) {
            console.error('令牌验证失败:', verifyError);
            if (verifyError.name === 'JsonWebTokenError') {
                throw new AppError('无效的认证令牌', StatusCodes.UNAUTHORIZED);
            } else if (verifyError.name === 'TokenExpiredError') {
                throw new AppError('令牌已过期', StatusCodes.UNAUTHORIZED);
            } else {
                throw verifyError;
            }
        }
    } catch (error) {
        console.error('认证中间件错误:', error);
        next(error);
    }
};

// 验证角色权限
exports.authorizeRole = (roles) => {
    return (req, res, next) => {
        try {
            if (!req.user) {
                throw new AppError('未认证', StatusCodes.UNAUTHORIZED);
            }

            if (!roles.includes(req.user.role)) {
                throw new AppError('权限不足', StatusCodes.FORBIDDEN);
            }

            next();
        } catch (error) {
            next(error);
        }
    };
};